﻿using System;
using System.Threading;
using System.Windows.Media.Animation;
namespace Trackr.GUI.Extensions
{
	public static class WindowExtensions
	{
		/// <summary>
		/// Will load the loadDelegate in a seperate thread and execute the processDelegate in the dispatcher thread
		/// </summary>
		/// <typeparam name="T">The type of object returned from the loadDelegate</typeparam>
		/// <param name="loadDelegate">The function used to get data</param>
		/// <param name="processDelegate">The callback to execute on the dispatcher thread with the data returned from the loadDelegate</param>
		public static void CallbackInvoke<T>(this System.Windows.Window window, Func<T> loadDelegate, Action<T> processDelegate) where T : class
		{
			ThreadStart start = () =>
			{
				T obj = loadDelegate();
				window.Dispatcher.BeginInvoke((Action)(() =>
				{
					processDelegate(obj);
				}), System.Windows.Threading.DispatcherPriority.Background);
			};
			new Thread(start).Start();
		}
		/// <summary>
		/// Will execute the Dispatcher on the window thread
		/// </summary>
		/// <param name="loadDelegate">The action to process on the window thread</param>
		public static void Invoke(this System.Windows.Window window, Action loadDelegate)
		{
			window.Dispatcher.BeginInvoke((Action)(() =>
			{
				loadDelegate();
			}), System.Windows.Threading.DispatcherPriority.Background);
		}
		/// <summary>
		/// Will make run an action in a seperate thread
		/// </summary>
		/// <param name="window"></param>
		/// <param name="loadDelegate"></param>
		public static void AsyncCall(this System.Windows.Window window, Action loadDelegate)
		{
			ThreadStart start = () =>
			{
				if (loadDelegate == null)
					return;
				loadDelegate();
			};
			new Thread(start).Start();
		}
		public static void FadeOut(this System.Windows.Window window, double duration = 100)
		{
			window.Invoke(() =>
			{
				DoubleAnimation opacityAnimation = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(duration));
				opacityAnimation.Completed += (sender, e) =>
				{
					window.Hide();
				};
				window.BeginAnimation(System.Windows.UIElement.OpacityProperty, opacityAnimation);

			});
		}
		public static void FadeIn(this System.Windows.Window window, double duration = 100)
		{
			window.Invoke(() =>
			{
				window.Opacity = 0;
				window.Show();
				DoubleAnimation opacityAnimation = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(duration));
				window.BeginAnimation(System.Windows.UIElement.OpacityProperty, opacityAnimation);
			});
		}
	}
}
